package com.itheima.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author Jt
 * @date 2021/4/7 20:45
 */
//@Component
//@Order(1)
public class LoginFilter implements GlobalFilter {

    /**
     * @param exchange 封装了请求对象 和 响应对象
     * @param chain    过滤器链
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
//        1.获取 请求对象 和 响应对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
//        2.根据请求头对象获取请求头(access-token)信息
        HttpHeaders headers = request.getHeaders();
        String accessToken = headers.getFirst("access-token");
//        3.判断access-token是否等于admin
        if ("admin".equals(accessToken)) {
//        4.等于 就放行这个请求
            return chain.filter(exchange); // 放行请求
        } else {
//        5.不等于 终止请求 并且设置响应码为401
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete(); // 终止响应
        }
    }

}
